HI 大家今天過得好嗎?
今天要來動手做個sidecar
以下這張來自官網的圖很清楚地解釋了sidecar on K8s的運作模式
大部分的pod只運行一個container, 但在某些情況下
我們必須要在一個pod運行兩個以上的containers, 這種multi-container的模式又可以衍伸至三種design patterns:
此圖出自這裡, 這張圖蠻清楚的描述了三種模式的不同,但由於篇幅以及時間關係,我就先講sidecar mode
這邊就利用上面文件裡的範例寫一個帶有nginx sidecar的pod yaml.
apiVersion: v1
kind: Pod
metadata:
name: pod-with-sidecar
spec:
# Create a volume called 'shared-logs' that the
# app and sidecar share.
volumes:
- name: shared-logs
emptyDir: {}
# In the sidecar pattern, there is a main application
# container and a sidecar container.
containers:
# Main application container
- name: app-container
# Simple application: write the current date
# to the log file every five seconds
image: alpine # alpine is a simple Linux OS image
command: ["/bin/sh"]
args: ["-c", "while true; do date >> /var/log/app.txt; sleep 5;done"]
# Mount the pod's shared log file into the app
# container. The app writes logs here.
volumeMounts:
- name: shared-logs
mountPath: /var/log
# Sidecar container
- name: sidecar-container
# Simple sidecar: display log files using nginx.
# In reality, this sidecar would be a custom image
# that uploads logs to a third-party or storage service.
image: nginx:1.7.9
ports:
- containerPort: 80
# Mount the pod's shared log file into the sidecar
# container. In this case, nginx will serve the files
# in this directory.
volumeMounts:
- name: shared-logs
mountPath: /usr/share/nginx/html # nginx-specific mount path
在這邊請注意 volumes 裡的 emptyDir 是建立pod時會自動生成的一個目錄,該pod下所有container都可以讀取這目錄的內容
直接創建:
跑起來之後下這個指令查看pod的詳細內容:
接著透過詳細內容中的訊息分別進入兩個containers中查看紀錄logs的目錄:
可以看到在app-container產生的時間log被同步進nginx這個container了
這就是最簡單的sidecar mode
下篇來講app level的log收集
官方文件-Pod Overview:
https://kubernetes.io/docs/concepts/workloads/pods/pod-overview/
Multi-container design pattern:https://matthewpalmer.net/kubernetes-app-developer/articles/multi-container-pod-design-patterns.html
這邊的 design patterns 是針對微服務設計的嗎 ?
是針對 pod 的特性設定的。當一個 pod 裡可以佈署多個 container,我們可以拆分不同功能到各個 container 中,然後套用軟體工程中的拆分模式,如:adapter, facade,來設計這些 container